<template>
    <div>
      <!--      可拼团商品列表-->
      <div>
        <el-table
          :data="groupGoodList"
          style="width: 100%">
          <el-table-column
            prop="goodName"
            label="商品名"
            width="180">
          </el-table-column>
          <el-table-column
            label="图片"
            width="180">
            <template slot-scope="scope">
              <el-image :src="scope.row.imageUrl" style="width: 80px;height: 60px"></el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="groupContent"
            label="简介">
          </el-table-column>
          <el-table-column
            prop="voliadNumber"
            label="可拼人数">
          </el-table-column>
          <el-table-column
            label="结束时间"
            style="width: 400px" >
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.endTime"
                type="datetime">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column
            label="参与">
            <template slot-scope="scope">
              <el-button @click="checkMore(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <a :href="url"><el-button id="q" @click="toUrl" ref="home">点击</el-button></a>
      </div>
    </div>
</template>
<script>
import { shareUrl, findGoodList, findUser, goUrl } from '@/api/consumer/consumer'
export default {
  name: 'Index',
  data() {
    return {
      // webSocket
      socket: {
        lockReconnect: false, // 是否真正建立连接
        timeout: 58 * 1000, // 58秒一次心跳
        timeoutObj: null, // 心跳心跳倒计时
        serverTimeoutObj: null, // 心跳倒计时
        timeoutnum: null // 断开 重连倒计时
      },
      // 调用成功的表单
      payResult: '',
      // 详情
      dialogTableVisibleMore: false,
      // 弹窗
      dialogTableVisible: false,
      // 支付
      dialogTableVisiblePay: false,
      // 可拼团商品
      groupGoodList: [],
      // 可拼团商品sku
      groupGoodSkuList: [],
      // 订单
      order: {
        subject: ''
      },
      // 用户
      user: {
        id: ''
      },
      groupId: '',
      // 拼团记录
      groupRecordList: [],
      // 链接
      urlVo: {
        url: ''
      },
      // 跳转路由
      url: '',
      // 拼团商品
      groupGood: {}
    }
  },
  created() {
    this.init()
    this.list()
    this.initWebSocket()
  },
  methods: {
    // 路由跳转
    toUrl() {
      window.location.href = this.url
    },
    // 初始化
    init() {
      goUrl().then(res => {
        if (res.data !== null) {
          this.url = res.data
          this.trigger(this.toUrl())
        }
      })
    },
    // 分享
    share() {
      var url = window.location.href + '/' + this.groupId
      this.urlVo.url = url
      shareUrl(this.urlVo).then(res => {
        this.urlVo.url = res.data
      })
    },
    // 查找商品列表
    list() {
      findGoodList().then(res => {
        this.groupGoodList = res.data
      })
    },
    // 查看详情
    checkMore(val) {
      console.log(val)
      this.groupId = val.id
      this.$router.push({
        path: '/consumer/homePage',
        query: {
          group: val
        }
      })
    },
    currentTime() {
      setInterval(this.formatDate, 500)
    },
    initWebSocket() {
      // 初始化weosocket
      findUser().then(res => {
        this.user = res.data
        this.user.username = 'User:' + this.user.id
        const wsUrl = 'ws://localhost:9214/webSocket/' + this.user.username
        if ('WebSocket' in window) {
          this.websocket = new WebSocket(wsUrl)
          // 客户端接收服务端数据时触发
          this.websocket.onmessage = this.websocketonmessage
          // 连接建立时触发
          this.websocket.onopen = this.websocketonopen
          // 通信发生错误时触发
          this.websocket.onerror = this.websocketonerror
          // 连接关闭时触发
          this.websocket.onclose = this.websocketclose
        } else {
          console.log('当前浏览器不支持webSocket')
        }
      })
    },
    // 连接建立时触发
    websocketonopen() {
      // 开启心跳
      this.start()
      // 连接建立之后执行send方法发送数据
      // let actions = {"room":"007854ce7b93476487c7ca8826d17eba","info":"1121212"};
      // this.websocketsend(JSON.stringify(actions));
    },
    // 通信发生错误时触发
    websocketonerror() {
      console.log('出现错误')
      this.reconnect()
    },
    // 客户端接收服务端数据时触发
    websocketonmessage(e) {
      console.log(e)
      console.log(e.data)
      this.$message.success(e.data)
      // 收到服务器信息，心跳重置
      this.reset()
    },
    websocketsend(Data) {
      // 数据发送
      this.websocket.send(Data)
    },
    // 连接关闭时触发
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
      // 重连
      this.reconnect()
    },
    reconnect() {
      // 重新连接
      var that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function() {
        // 新连接
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    reset() {
      // 重置心跳
      var that = this.socket
      // 清除时间
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      // 重启心跳
      that.start()
    },
    start() {
      // 开启心跳
      console.log('开启心跳')
      var self = this.socket
      self.timeoutObj && clearTimeout(self.timeoutObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeoutObj = setTimeout(function() {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (this.websocket.readyState === 1) {
          // 如果连接正常
          // self.ws.send("heartCheck"); //这里可以自己跟后端约定
        } else {
          // 否则重连
          this.reconnect()
        }
        self.serverTimeoutObj = setTimeout(function() {
          // 超时关闭
          self.websocket.close()
        }, self.timeout)
      }, self.timeout)
    }
  }
}
</script>
<style scoped>
</style>
